﻿define(function (require, exports, module) {
    var Canvas = require('util/canvas');
    var ImageStorage = require('util/imageStorage');
    var Config = require('util/config');
    var IRole = require('newRole/iRole');

    var MAX_STATUS = 20;
    var MAX_PROPERTY = 10;
    var STATUS = ['vit', 'str', 'sta', 'agi'];
    var m_character;
    var m_backCallback;
    var m_status;
    var m_propertySettings;
    var m_propertyImageIds = [];
    var m_brokeRules = [{
        validate: function () { return getTxtName().val().trim() == ''; }, groupId: '#nameMessageGroup'
    }, {
        validate: function () { return 0 < m_status; }, groupId: '#statusMessageGroup'
    }, {
        validate: function () { return 0 < m_propertyImageIds.length; }, groupId: '#propertyMessageGroup'
    }];

    exports.loadCreate = function (character) {
        $.extend(character.data, {
            expressionUpId: Config.character.expression.up.FIRST,
            expressionDownId: Config.character.expression.down.FIRST,
            name: '', vit: 0, str: 0, sta: 0, agi: 0, land: 0, water: 0, fire: 0, wind: 0
        });
        m_status = MAX_STATUS;
        m_propertySettings = [
            { name: 'land', inverse: 'fire', y: 254, ids: [] },
            { name: 'water', inverse: 'wind', y: 278, ids: [] },
            { name: 'fire', inverse: 'land', y: 302, ids: [] },
            { name: 'wind', inverse: 'water', y: 326, ids: [] }
        ];

        m_character = character;
        this.reloadCreateAsync().start();
    };

    exports.reloadCreateAsync = eval(Wind.compile('async', function () {
        $await(IRole.renderCreateAsync(m_character));

        Canvas.get('#decide').on('click', function () {
            this.hide();
            var result = true;
            for (var i = 0, brokeRule; brokeRule = m_brokeRules[i]; i++) {
                if (brokeRule.validate()) {
                    Canvas.get(brokeRule.groupId)[0].show();
                    getTipText().setText('');
                    getTipText().getLayer().draw();
                    result = false;
                    break;
                }
            }
            if (result) {
                m_character.data.name = getTxtName().val().trim();
                getTxtName().remove();
                var Birthplace = require('newRole/birthplace');
                Birthplace.setBackCallback(function () {
                    exports.reloadCreateAsync().start();
                });
                Birthplace.loadAsync(m_character).start();
            }
        });

        Canvas.get('#back').on('click', m_backCallback);

        getTxtName().val(m_character.data.name);

        setExpressionEvent();
        setStatusEventAndValue();
        setPropertyEventAndValue();
    }));

    function setExpressionEvent() {
        $.each(['Up', 'Down'], function () {
            (function (name) {
                var imageId = 'expression' + name, property = imageId + 'Id';
                Canvas.get('#expression' + name + 'Left').on('click', function () {
                    m_character.data[property]--;
                    m_setExpressionImageAsync(imageId, m_character['getExpression' + name + 'Path']()).start();
                });
                Canvas.get('#expression' + name + 'Right').on('click', function () {
                    m_character.data[property]++;
                    m_setExpressionImageAsync(imageId, m_character['getExpression' + name + 'Path']()).start();
                });
            })(this);
        });
    };

    var m_setExpressionImageAsync = eval(Wind.compile('async', function (id, path) {
        var img = $await(ImageStorage.getAsync(path));
        Canvas.get('#' + id)[0].setImage(img);
    }));

    function setStatusEventAndValue() {
        var statusText = Canvas.get('#totalStatus')[0];

        $.each(STATUS, function () {
            (function (name) {
                Canvas.get('#' + name + 'Left').on('click', function () {
                    if (0 < m_character.data[name]) {
                        m_character.data[name]--;
                        m_status++;
                        Canvas.get('#' + name)[0].setText(m_character.data[name]);
                        statusText.setText(m_status);
                    }
                });
                Canvas.get('#' + name + 'Right').on('click', function () {
                    if (0 < m_status) {
                        m_character.data[name]++;
                        m_status--;
                        Canvas.get('#' + name)[0].setText(m_character.data[name]);
                        statusText.setText(m_status);
                    }
                });
            })(this);
            Canvas.get('#' + this)[0].setText(m_character.data[this]);
        });
        statusText.setText(m_status);
    };

    function setPropertyEventAndValue() {
        m_propertyImageIds = [];
        for (var i = 0; i < MAX_PROPERTY; i++) {
            m_propertyImageIds.push('#' + i);
        }

        $.each(m_propertySettings, function () {
            (function (settings) {
                Canvas.get('#' + settings.name + 'Left').on('click', function () {
                    if (0 < m_character.data[settings.name]) {
                        m_character.data[settings.name]--;
                        var id = settings.ids.pop();
                        m_propertyImageIds.push(id);
                        Canvas.get(id)[0].hide();
                        getTotalPropertyText().setText(m_propertyImageIds.length);
                    }
                    if (0 == m_character.data[settings.name]) {
                        Canvas.get('#' + settings.inverse + 'Left')[0].show();
                        Canvas.get('#' + settings.inverse + 'Right')[0].show();
                    }
                });
                Canvas.get('#' + settings.name + 'Right').on('click', function () {
                    if (0 == m_character.data[settings.name]) {
                        Canvas.get('#' + settings.inverse + 'Left')[0].hide();
                        Canvas.get('#' + settings.inverse + 'Right')[0].hide();
                    }
                    if (settings.ids.length < 10) {
                        if (0 == m_propertyImageIds.length) {
                            for (var i = 0, _settings; _settings = m_propertySettings[i]; i++) {
                                _settings != settings && 0 < _settings.ids.length && Canvas.get('#' + _settings.name + 'Left')[0].simulate('click');
                            }
                        }
                        m_character.data[settings.name]++;
                        var id = m_propertyImageIds.pop();
                        settings.ids.push(id);
                        setPropertyImagesAsync(settings).start();
                        getTotalPropertyText().setText(m_propertyImageIds.length);
                    }
                });
            })(this);
        });
        $.each(m_propertySettings, function () {
            var value;
            if (0 == (value = m_character.data[this.name])) return true;
            m_character.data[this.name] = 0;
            this.ids = [];
            for (var i = 0; i < value; i++) {
                Canvas.get('#' + this.name + 'Right')[0].simulate('click');
            }
        });
    };

    function getTotalPropertyText() { return Canvas.get('#totalProperty')[0]; }

    function getTipText() { return Canvas.get('#tipText')[0]; }

    function getTxtName() { return $('#txtName'); }

    var setPropertyImagesAsync = eval(Wind.compile('async', function (settings) {
        var img = $await(ImageStorage.getAsync(Config.images[settings.name.toUpperCase() + '_PROPERTY']));
        $.each(settings.ids.sort(), function (i) {
            Canvas.get(this)[0].setAttrs({
                image: img, visible: true, y: settings.y, x: 297 + i * 8
            });
        });
    }));

    exports.setBackCallback = function (callback) {
        m_backCallback = callback;
    };
});